package com.hp.utils.excel.handler;

import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import com.hp.utils.excel.ExcelConstraintResolve;
import com.hp.utils.excel.strategy.ConstraintTypeStrategy;
import com.hp.utils.excel.strategy.impl.BasicConstraintStrategyFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;


/**
 * @author hp
 */
@Slf4j
public record ConstraintSheetWriteHandler(List<ExcelConstraintResolve> resolveList) implements SheetWriteHandler {

    /**
     * Called before create the sheet
     */
    @Override
    public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        // 当前版本暂不需要此功能
    }

    /**
     * Called after the sheet is created
     */
    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        // 这里可以对cell进行任何操作
        Sheet sheet = writeSheetHolder.getSheet();

        DataValidationHelper helper = sheet.getDataValidationHelper();
        // 创建一个隐藏的sheet
        Workbook workbook = writeWorkbookHolder.getWorkbook();
        String sheetName = "hidden0";
        Sheet hiddenSheet = workbook.createSheet(sheetName);

        // 存储循环中带有自定义key的集合，用于后续循环从中获取
        Map<String, ExcelConstraintResolve> tempKeyMap = new HashMap<>();

        for (ExcelConstraintResolve resolve : resolveList) {

            ConstraintTypeStrategy strategy = BasicConstraintStrategyFactory.getStrategy(resolve.getType());
            if (Objects.isNull(strategy)) {
                log.info("不支持的类型 ：{}", resolve.getType());
                continue;
            }
            strategy.process(resolve, tempKeyMap, helper, hiddenSheet, sheet);

        }
        // 设置存储下拉列值得sheet为隐藏
        this.setHiddenSheet(workbook, sheetName);
    }

    /**
     * 隐藏下拉sheet
     */
    private void setHiddenSheet(Workbook workbook, String sheetName) {
        int hiddenIndex = workbook.getSheetIndex(sheetName);
        if (!workbook.isSheetHidden(hiddenIndex)) {
            workbook.setSheetHidden(hiddenIndex, true);
        }
    }


}